package toledo.post;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import toledo.rest.Course;
import toledo.rest.Entry;
import toledo.rest.Update;
import toledo.rest.User;
import toledo.util.DateManager;
import toledo.util.TwitterSearch;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class AddTweetServlet extends HttpServlet
{
	private static final long serialVersionUID=1L;
	
	private static final Logger log = Logger.getLogger(AddTweetServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		log.log(Level.INFO, "Cron job");
		String since_id = "119719744281640960";
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query("tweets").addSort("guid", Query.SortDirection.DESCENDING);
		List<Entity> tweets = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));
		// TODO: long vs. string on guid!
		if (!tweets.isEmpty())
			since_id = (tweets.get(0).getProperty("guid")).toString();
		
		/*
		for(Entity tweet:tweets)
			datastore.delete(tweet.getKey());
		
		List<Entity> entries = datastore.prepare(new Query("entries")).asList(FetchOptions.Builder.withLimit(10));
		for(Entity entry:entries)
			datastore.delete(entry.getKey());
			//*/
		
		//*
		List<Entity> courses = DatastoreServiceFactory.getDatastoreService().prepare(new Query(Course.DATABASE)).asList(FetchOptions.Builder.withDefaults());
		for(Entity course:courses)
		{
			createTweetEntitiesfromHastTag(course.getProperty(Course.HASHTAG).toString(),since_id,KeyFactory.keyToString(course.getKey()));
		}//*/
	}

	private void createTweetEntitiesfromHastTag(String hashtag,String since_id,String course_id)
	{
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		log.log(Level.INFO, "createTweetEntitiesfromHastTag");
		TwitterSearch ts = new TwitterSearch();
		JSONArray results = ts.getTweetsFromHashtag(hashtag,since_id);
		for (int i = 0; i < results.length(); i++)
		{
			JSONObject resultObj = null;
			try
			{
				resultObj = results.getJSONObject(i);
				
				DateTime parseDateTime = DateManager.fmt1.parseDateTime(resultObj.getString("created_at").split(", ")[1].trim());
				
				Entity user = DatastoreServiceFactory.getDatastoreService().prepare(new Query(User.DATABASE).addFilter(User.TWITTER_ID,FilterOperator.EQUAL,resultObj.getString("from_user"))).asSingleEntity();
				
				if(user!=null)
				{
					Entity entryEntity = new Entity("entries");
					entryEntity.setProperty(Entry.DATE,parseDateTime.toDate());
					entryEntity.setProperty(Entry.COURSE_ID,course_id);
					entryEntity.setProperty(Entry.REPLY_TO_ID,"");
					entryEntity.setProperty(Entry.TEXT,resultObj.getString("text"));
					entryEntity.setProperty(Entry.USER_ID,KeyFactory.keyToString(user.getKey()));
					entryEntity.setProperty(Entry.TYPE,Entry.TYPE_TWEET);
					datastore.put(entryEntity);
					
					Entity update = new Entity("updates");
					update.setProperty(Update.COURSE_ID,course_id);
					update.setProperty(Update.USER_ID,KeyFactory.keyToString(user.getKey()));
					update.setProperty(Update.ENTRY_ID,KeyFactory.keyToString(entryEntity.getKey()));
					update.setProperty(Update.TYPE,Update.TYPE_POST);
					datastore.put(update);
					
					Entity tweetEntity = new Entity("tweets");
					tweetEntity.setProperty("guid", resultObj.getString("id"));
					datastore.put(tweetEntity);
				}
				else
				{
					log.log(Level.INFO,"didn't find: "+resultObj.getString("from_user"));
				}
			}
			catch (JSONException e)
			{
				log.log(Level.SEVERE, "Json parse exception. Json=" + resultObj, e);
			}
		}
	}
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		doGet(req, resp);
	}
}
